<template>
  <view class="">
    <view class="u-m-30 u-text-center" style="font-weight: 600;">
      请选择所在地区
    </view>
    <view class='area-nav'>
      <scroll-view scroll-x class='choosed-area'>
        <view v-for="(choose, index) in choosedAreas" :key="index" v-if="choosedAreas.length"
          @click="onchangeChoosedItem(choose)" class="nav-li"
          :class="choose && choose.region_grade === areas[0].region_grade ? 'selected' : '' ">
          {{choose.local_name || '请选择'}}</view>
        <view class="nav-li" v-if="!choosedAreas.length || !finished">请选择</view>
      </scroll-view>
    </view>
    <view class='main'>
      <view v-if="!areas.length" style="height: 680rpx;" class="u-f-ajc">
        <u-empty mode="list" text="获取区域会员信息中...请稍等"></u-empty>
      </view>
      <scroll-view scroll-y class='main-ul' v-if="areas.length">
        <view class="main-li" :class="item.selected ? 'selected' : '' " v-for="(item, index) in areas" :key="index"
          @click="onchangeItem(item)">
          <text class='item'>{{item.local_name}}<text>（{{item.registed ? '已有' : '未选'}}）</text></text>
          <u-icon v-if="item.selected" name="checkmark" color="#f42424"></u-icon>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
  /**
   * 地区选择组件
   *
   * ===== 使用场景 ======
   * 所有选择地区的地方
   *
   * ===== 参数 =====
   * show         地区组件是否显示
   *
   * ===== 事件 =====
   * @addressSelectorChanged 选择地区时触发，把选择的新地区传给父组件
   * @closeRegionpicke  监听地区是否选择完毕，选择完毕后关闭地区组件弹出框
   */
  import * as API_Address from '@/api/address.js'
  export default {
    data() {
      return {
        id: 3,
        areas: [], //当前级别显示的地区
        selectedAreas: [], //存储当前选中项所属的地区列表
        choosedAreas: [], //选中的地区
        finished: false, //是否选择完毕
      }
    },
    props: {
      show: {
        type: Boolean,
        default: false
      }
    },
    mounted() {

    },
    watch: {
      //监听地区组件是否显示
      show: {
        handler(newVal) {
          if (newVal) {
            this.getAreasItems()
          }
        },
        immediate: true
      },
      //关闭地区组件
      finished() {
        if (this.finished) {
          this.$emit('closeRegionpicke', false)
        }
      },
      //把选择的地区传给父组件
      choosedAreas(newVal) {
        this.$emit('addressSelectorChanged', newVal)
      }
    },
    methods: {
      // 已选择的地区变化时触发
      onchangeChoosedItem(choose) {
        if (!choose.region_grade) return
        this.areas = this.selectedAreas[choose.region_grade - 1]
      },
      // 选择列表地区项变化时
      onchangeItem(item) {
        // console.log(item)
        // console.log(this.choosedAreas)
        if (this.choosedAreas[item.region_grade - 1] && this.areas[0].region_grade === item.region_grade && item.id ===
          this.choosedAreas[
            item.region_grade - 1].id) {
          console.log(111)
          return
        } else {
          console.log(222)
          this.choosedAreas.length = item.region_grade - 1
          if (this.choosedAreas[item.region_grade - 1]) {
            console.log(333)
            this.choosedAreas[item.region_grade - 1] = item
          } else {
            console.log(444)
            this.choosedAreas = this.choosedAreas.concat(item)
          }
          this.areas.forEach(key => {
            if (item.id === key.id) {
              key.selected = true
            } else {
              key.selected = false
            }
          })
          item.selected = true
          this.finished = item.region_grade === 4
          if (item.region_grade === 4) {
            return
          }
          this.id = item.id
          this.getChongfu()
        }
      },
      
      getChongfu() {
        console.log(this.id, this.areas)
        let response = this.areas.find(item => item.id == this.id).children
        if (response && Array.isArray(response) && response.length) {
          response.forEach(key => {
            key.selected = false
            key.region_grade = key.level
          })
          this.areas = response
          console.log(this.areas)
          if (this.selectedAreas[response[0].region_grade - 1]) {
            if (response[0].region_grade === this.selectedAreas[response[0].region_grade - 1][0]
              .region_grade) {
              this.selectedAreas[response[0].region_grade - 1] = response
            }
          } else {
            this.selectedAreas.push(response)
          }
        } else {
          this.finished = true
        }
      },
      
      //获取地区列表
      getAreasItems() {
        let that = this
        uni.request({
          url: `http://api.base.ruixingzhubao.xjkuang.com/regions/depth/${this.id}`,
          header: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': uni.getStorageSync('accessToken')
          },
          success: res => {
            var response = res.data
            if (response && Array.isArray(response) && response.length) {
              response.forEach(key => {
                key.selected = false
                key.region_grade = key.level
              })
              that.areas = response
              console.log(that.areas)
              if (that.selectedAreas[response[0].region_grade - 1]) {
                if (response[0].region_grade === that.selectedAreas[response[0].region_grade - 1][0]
                  .region_grade) {
                  that.selectedAreas[response[0].region_grade - 1] = response
                }
              } else {
                that.selectedAreas.push(response)
              }
            } else {
              that.finished = true
            }
          },
          fail: () => {},
          complete: () => {}
        });
      },
      getAreasItems2() {
        API_Address.getAreas(this.id).then(response => {
          if (response && Array.isArray(response) && response.length) {
            response.forEach(key => {
              key.selected = false
            })
            this.areas = response
            if (this.selectedAreas[response[0].region_grade - 1]) {
              if (response[0].region_grade === this.selectedAreas[response[0].region_grade - 1][0].region_grade) {
                this.selectedAreas[response[0].region_grade - 1] = response
              }
            } else {
              this.selectedAreas.push(response)
            }
          } else {
            this.finished = true
          }
        })
      },
    }
  }
</script>

<style lang="scss" scoped>
  .area-nav {
    position: relative;
    width: 100%;
    height: 60rpx;

    .choosed-area {
      position: relative;
      width: 100%;
      height: 50rpx;
      border-bottom: 2rpx solid #dddddd;
      margin-top: -2rpx;
      padding-left: 20rpx;
      overflow-y: hidden;
      overflow-x: scroll;
      white-space: nowrap;

      .nav-li {
        display: inline-block;
        margin-right: 40rpx;
        padding-bottom: 8rpx;

        &.selected {
          color: #f42424;
          border-bottom: 4rpx solid #f42424;
        }
      }
    }
  }

  .main {
    position: relative;
    left: 0;
    width: 100%;
    height: 84%;

    .main-ul {
      float: left;
      width: 100%;
      height: 680rpx;
      margin-bottom: 20rpx;

      .main-li {
        padding-top: 20rpx;
        padding-bottom: 20rpx;
        margin-left: 20rpx;
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;

        &.selected .item {
          color: #f42424;
        }
      }
    }
  }
</style>
